#ifdef __cplusplus
extern "C"{
#endif


#include "xs_def.h"
#include "xs_io.h"
#include "xs_log.h"
#include "xs_zlog.h"


int __xs_close_fd__(int __f)
{
	return close(__f);
}
int __xs_set_non_blocking__( int __f )
{
	int __flags__;

	/* According to the Single UNIX Spec, the return value for F_GETFL should
	never be negative. */
	if ((__flags__ = fcntl(__f, F_GETFL)) < 0){
		xs_logd("fcntl(F_GETFL) failed for fd %d: %s",
		__f, safe_strerror(errno));
		return -1;
	}
	
	if (fcntl(__f, F_SETFL, (__flags__ | O_NONBLOCK)) < 0){
		xs_logd("fcntl failed setting fd %d non-blocking: %s",
		__f, safe_strerror(errno));
		return -1;
	}
	
	return 0;
}


int __xs_writev__ ( int  __f, const struct iovec *__iov, int __cnt)
{
    int __nbytes__;
	
    __nbytes__ = writev(__f, __iov, __cnt);
 
    if (__nbytes__ < 0)
		xs_logd("%s", strerror (errno));	
	
    return __nbytes__;
}

int __xs_readv__( int __f, struct iovec *__iov, int __cnt)
{
	int __nbytes__;

	if(__iov == NULL) return (__nbytes__ = 0);
	
	__nbytes__ = readv(__f, __iov, __cnt);
	if(__nbytes__ < 0)
		xs_logd("%s", strerror (errno));	
	
	return (int)__nbytes__;
}


/* Read nbytes from fd and store into ptr. */
int __xs_read_n__ (int __f, void *__p, int __nbytes)
{
	int __nleft__;
	int __nread__ ;

	__nleft__ = __nbytes;

	while (__nleft__ > 0){
		
		__nread__ = read (__f, __p, __nleft__);

		if (__nread__ < 0){
			//xs_logd("%s", strerror (errno));	
			return (__nread__);
		}
		__nleft__ -= __nread__;
		__p += __nread__;
	}

	return (__nbytes - __nleft__);
}

/* Write nbytes from ptr to fd. */
int __xs_write_n__(int __f, void *__p, int __nbytes)
{
	int __nleft__;
	int __nwritten__;

	__nleft__ = __nbytes;

	while (__nleft__ > 0){
		
		__nwritten__ = write(__f, __p, __nleft__);

		if (__nwritten__ < 0){
			//xs_logd("%s", strerror (errno));	
			return (__nwritten__);
		}

		__nleft__ -= __nwritten__;
		__p += __nwritten__;
	}
	
	return (__nbytes - __nleft__);
}


#ifdef __cplusplus
}
#endif

